//
//  FIHttpAPIHelper.m
//  Magpie
//
//  Created by 100TV protocal on 12-11-14.
//
//

#import "FIHttpAPIHelper.h"
#import "FIHttpRequest.h"
#import "FIStringHelper.h"
#import "Reachability.h"
#import "FIUIUtility.h"
#import <CommonCrypto/CommonDigest.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

NSString* sourceId(){
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
	static NSString* _sourceid=nil;
	if(_sourceid==nil){
		NSError* error=nil;
		NSString* path=[[NSBundle mainBundle] pathForResource:@"sourceid" ofType:@"dat"];
		_sourceid=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
		assert(_sourceid!=nil);
		_sourceid=[[_sourceid stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] retain];
		//!! NSLog(@"sourceid=%@ error=%@",_sourceid, error);
	}
	[pool release];
	return _sourceid;
}
NSString* appName(){
	NSString *ret = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
	return ret;
}
NSString* appVer(){
	NSString* ret=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
	return ret;
}
NSString* uid(){
	NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
	NSString* uid=[userDefaults stringForKey:@"uid"];
	return uid;
}
void setUid(NSString* auid){
	assert(auid!=nil);
	NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
	[userDefaults setObject:auid forKey:@"uid"];
	[userDefaults synchronize];
}


NSString* urlWithPath(NSString* path){
	return [NSString stringWithFormat:@"%@%@",YK_SERVER_HOST,path];
}

////////////////////////////////////////////////////
@interface FIHttpRequestHelper : NSObject<FIHttpRequestDelegate> {
	id object;
	SEL action;
}
/*
 object:
 网址内容下载完成后调用此对象的action方法，action方法格式同下
 action:
 -(void)****:(GDataXMLDocument*) xmlDoc params:(NSDictionary*) params;
*/
-(id) initWithObject:(id)aobj action:(SEL)aaction;
@end

@implementation FIHttpRequestHelper
-(id) initWithObject:(id)aobj action:(SEL)aaction{
	if(self=[super init]){
		//assert(aobj!=nil);
		object=[aobj retain];
		action=aaction;
	}
	return self;
}
-(void) dealloc{
	[object release];
	[super dealloc];
}
-(void) onLoadFinished:(NSString *)responseString {
#ifndef NDEBUG
	NSLog(@"-(void) onLoadFinished:(NSString *)responseString enter... responseString:\n%@",responseString);
#endif
	//assert(responseString!=nil);
	[object performSelector:action withObject:responseString];
}
-(void) onLoadFailed:(NSError *)error{
	//!! NSLog(@"!!!!warning %@-(void) onLoadFailed:(NSError *)error=%@ enter...",[self class],error);
	[object performSelector:action withObject:error];
}
@end

@interface FIHttpRequestHelper2 : FIHttpRequestHelper {
	NSDictionary* params;
}
-(id) initWithObject:(id)aobj action:(SEL)aaction params:(NSDictionary*) aparams;
@end
@implementation FIHttpRequestHelper2
-(id) initWithObject:(id)aobj action:(SEL)aaction params:(NSDictionary*) aparams{
	if(self=[super initWithObject:aobj action:aaction]){
		params=[aparams retain];
	}
	return self;
}
-(void) dealloc{
	[params release];
	[super dealloc];
}
-(void) onLoadFinished:(NSString *)responseString {
#ifndef NDEBUG
	NSLog(@"-(void) onLoadFinished:(NSString *)responseString enter... responseString:\n%@",responseString);
#endif
	[object performSelector:action withObject:responseString withObject:params];
}
-(void) onLoadFailed:(NSError *)error{
	//!! NSLog(@"!!!!warning %@-(void) onLoadFailed:(NSError *)error=%@ enter...",[self class],error);
	[object performSelector:action withObject:error withObject:params];
}
@end

NSString* joinStringFromDictionary(NSDictionary * input) {
	NSArray* keyArray=[input allKeys];
	NSArray *sortedArray=[keyArray sortedArrayUsingSelector:@selector(compare:)];
	NSMutableString *resultString;
	resultString = [[NSMutableString alloc] initWithString:@""];
	for(id key in sortedArray){
		id val=[input objectForKey:key];
		[resultString appendFormat:@"%@%@",key,val];
	}
	return [resultString autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////
static NSMutableDictionary* commonParams;
@implementation FIHttpAPIHelper

+(void) initialize{
	commonParams=[[NSMutableDictionary alloc] init];
}
+(void) setCommonParam:(NSString *)key value:(id)value{
	[commonParams setValue:value forKey:key];
}
+(id) commonParam:(NSString*) key{
	return [commonParams objectForKey:key];
}

/*
 */
+(NSMutableDictionary*) fixParams:(NSDictionary*) oriParams{
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
	if(oriParams==nil){
		oriParams=[NSDictionary dictionary];
	}
	
	NSString* appver=appVer();
	NSString* timestamp=nowTimestamp();
	//统计字段(sourceid@appkey@应用名_平台名_版本号_自定义)
	NSString* ttid=[NSString stringWithFormat:@"%@@%@@VANCLHD_%@_%@",sourceId(),YK_APP_KEY,YK_PLATFORM,appver];
	NSMutableDictionary* params=[[NSMutableDictionary alloc] initWithObjectsAndKeys:
								 YK_COMM_PROTOCAL_VER,@"ver",
								 @"MD5",@"sign_method",
								 stringOrEmpty(timestamp),@"t",
								 YK_APP_KEY,@"appkey",
								 YK_PLATFORM,@"platformn",
								 ttid,@"ttid",
								 stringOrEmpty(sourceId()),@"source",
								 @"json",@"format",
								 nil];
	[params addEntriesFromDictionary:commonParams];
	[params addEntriesFromDictionary:oriParams];
	//不提交 以! 开头的key
	for(NSString* key in [params allKeys]){
		if([key hasPrefix:@"!"]){
			[params removeObjectForKey:key];
		}
	}
	NSString* aa = joinStringFromDictionary(params);
	NSString* signsrc=[NSString stringWithFormat:@"%@%@",YK_APP_SECURITY,aa];
	NSString* sign=YKMD5(signsrc);
	
	[params setObject:stringOrEmpty(sign) forKey:@"sign"];
	
	[pool release];
	[params autorelease];
	return params;
}
+(NSDictionary*) extraHeaders{
	return nil;
}

+(void) startLoad:(NSString *)url extraParams:(NSDictionary *)extraParams object:(id)object action:(SEL)action{
	//assert(object!=nil);

}

+(void) startLoad2:(NSString *)url extraParams:(NSDictionary *)extraParams object:(id)object action:(SEL)action{
	//assert(object!=nil);
    NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
    
	NSMutableDictionary* fixParams=[FIHttpAPIHelper fixParams:extraParams];
	FIHttpRequestHelper2* helper=[[FIHttpRequestHelper2 alloc] initWithObject:object action:action params:extraParams];
	[FIHttpRequest startLoadUrlString:url delegate:helper params:fixParams extraHeaders:[FIHttpAPIHelper extraHeaders]];
	[helper release];
    
	[pool release];
}

@end





/*
 返回当前时间
 */
NSString* nowTimestamp(){
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
	NSString* format=@"yyyyMMddHHmmss";
	assert(format!=nil);
	NSDate* nowDate=[NSDate date];
	NSDateFormatter* dateFormater=[[NSDateFormatter alloc] init];
	[dateFormater setDateFormat:format];
	[dateFormater stringFromDate:nowDate];
	NSString* timestamp=[[dateFormater stringFromDate:nowDate] copy];
	[dateFormater release];
	[pool release];
	return [timestamp autorelease];
}

NSString* YKMD5( NSString *str ) {
	const char *cStr = [str UTF8String];
	unsigned char result[CC_MD5_DIGEST_LENGTH];
	
	CC_MD5( cStr, strlen(cStr), result );
	
	return [[NSString
			 stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			 result[0], result[1],
			 result[2], result[3],
			 result[4], result[5],
			 result[6], result[7],
			 result[8], result[9],
			 result[10], result[11],
			 result[12], result[13],
			 result[14], result[15]
			 ] lowercaseString];
}

/*
 获取运行商名称
 */
NSString* carrierName(){
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
	NSString* carrierName=nil;
    if (nil!=NSClassFromString(@"CTTelephonyNetworkInfo")){
		//
		CTTelephonyNetworkInfo* netInfo=[[CTTelephonyNetworkInfo alloc] init];
		if(netInfo!=nil){
			CTCarrier* carrier=netInfo.subscriberCellularProvider;
			if(carrier!=nil){
				carrierName=[carrier.carrierName copy];
			}
		}
		[netInfo autorelease];
	}
	[pool release];
	return [carrierName autorelease];
}

BOOL detectNetwork(){
	BOOL ret=NO;
	Reachability* reach=[Reachability reachabilityForInternetConnection];
	if(reach!=nil && [reach isReachable]){
		ret=YES;
	}
	return ret;
}

/*
 检测网络，如果没法连接internet 提示“”
 返回
 YES:网络通
 no:	网络不通
 */

BOOL detectNetworkAndTip(){
	BOOL ret=detectNetwork();
	if(!ret){
		alert(@"您现在没有网络连接。");
	}
	return ret;
}

/*
 重新请求，或取消
 */
void retryRequestOrCancle(id target,SEL action){
	alert3(@"请求超时，您的网络可能有问题哦~", @"知道了",@"重试", target, action);
}









